//  Copyright © 2014 Allen County Public Library.

//        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
package us.in.lib.acpl.Mobile_ACPL;


import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;

import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.item.SearchResultTitle;
import us.in.lib.acpl.Mobile_ACPL.models.BestSellerDisplayInfo;
import us.in.lib.acpl.Mobile_ACPL.models.BestSellerTitle;
import us.in.lib.acpl.Mobile_ACPL.models.BestSellerTitlesResponse;
import us.in.lib.acpl.Mobile_ACPL.parents.BaseActivity;
import us.in.lib.acpl.Mobile_ACPL.rest.SirsiClient;
import us.in.lib.acpl.Mobile_ACPL.ws.BestSellerSearchHandler;
import us.in.lib.acpl.Mobile_ACPL.ws.SearchCatalogHandler;



@EActivity(R.layout.best_seller_list)
public class BestSellerListActivity extends BaseActivity implements FeaturedTitleList {

	private BestSellerSearchHandler handler;

	@RestService
	SirsiClient client;
	
	@ViewById
	ListView listView;
	
	List<BestSellerTitle> titles;
	BestSellerTitlesAdapter adapter;
	String listId;
	
	List<Bitmap> images;

    //ACPL: Removed Syndetics url
	public static final String URL_START = "";
	public static final String IMAGE_URL_END = "";
	
	@AfterViews
	public void afterViews(){
		this.getActionBar().setTitle("   Featured Titles");
		titles = new ArrayList<BestSellerTitle>();
		adapter = new BestSellerTitlesAdapter();
		listView.setAdapter(adapter);
		listId = getIntent().getStringExtra("listId");
		images = new ArrayList<Bitmap>();
		
		handler = new BestSellerSearchHandler(this);
		Mobile_ACPL app = (Mobile_ACPL) this.getApplication();
		app.setBestSellerSearchHandler(handler);
		
		getTitles();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}
	
	@Background
	public void getTitles(){
		BestSellerTitlesResponse response = client.getBestSellerTitles(listId);
		getTitlesComplete(response);
	}
	@UiThread
	public void getTitlesComplete(BestSellerTitlesResponse response){
		this.titles=response.bestSellerTitleInfo;
		adapter.notifyDataSetChanged();
		listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				BestSellerTitle title = titles.get(position);
				
				String searchString = title.searchString+"+"+title.author;
				search(searchString);
				
				
			}
			
		});
		
	}
	
	public void handleSearchResults(List<SearchResultTitle> results){
		Intent intent = new Intent(this, SearchResultsActivity.class);
		intent.putExtra("source", "BestSellerListActivity");
		startActivity(intent);
	}
	
	public void search(String searchString) {



			EasyTracker.getTracker().sendEvent("Search", "BestSellerList", null, null);


			handler.search(searchString,
					SearchCatalogHandler.RESULTS_PER_PAGE, "title",
					null, null);

		
	}
	
	public class BestSellerTitlesAdapter extends BaseAdapter{
	

		
		@Override
		public int getCount() {

			return titles.size();
		}

		@Override
		public Object getItem(int position) {

			return titles.get(position);
		}

		@Override
		public long getItemId(int position) {
	
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			BestSellerTitle title = titles.get(position);
			LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
			convertView = inflater.inflate(R.layout.best_seller_list_item, null);
			
			if (position >= images.size()) {

				new GetImageTask().execute(convertView, position);

				
			} else {
				View v = convertView.findViewById(R.id.coverBar);
				v.setVisibility(View.GONE);
				ImageView iv = (ImageView) convertView.findViewById(R.id.smallCover);

				Bitmap image = images.get(position);
				if (image == null) {
					iv.setImageResource(R.drawable.book);
				} else {
					iv.setImageBitmap(image);
				}
			}
			
			
			
			
			TextView tv = (TextView)convertView.findViewById(R.id.searchResultLine1);
			tv.setText(title.title);
			
			tv = (TextView)convertView.findViewById(R.id.searchResultLine2);
			tv.setText(title.author);
			
			return convertView;
		}
		
	}
	
	
	private class GetImageTask extends AsyncTask<Object, Void, Object[]> {

		@Override
		protected Object[] doInBackground(Object... args) {

			View view = (View) args[0];
			Integer pos = (Integer) args[1];

			String urlString;

			urlString = URL_START + titles.get(pos).ISBN
					+ IMAGE_URL_END;

			Bitmap coverImage = null;
			try {
				URL newurl = new URL(urlString);
				coverImage = BitmapFactory.decodeStream(newurl.openConnection()
						.getInputStream());

			} catch (Exception e) {
				e.printStackTrace();
			}
			Object[] arr = new Object[3];
			arr[0] = coverImage;
			arr[1] = view;
			arr[2] = pos;
			return arr;

		}

		@Override
		protected void onPostExecute(Object[] arr) {
			Bitmap image = (Bitmap) arr[0];
			View view = (View) arr[1];
			Integer pos = (Integer) arr[2];
			setImage(image, view, pos);

		}

	}
	
	public void setImage(Bitmap image, View rowView, Integer pos) {

		View v = rowView.findViewById(R.id.coverBar);
		v.setVisibility(View.GONE);
		ImageView iv = (ImageView) rowView.findViewById(R.id.smallCover);

		if (image == null || image.getHeight() <= 1) {


				iv.setImageResource(R.drawable.book);



			if (pos >= images.size()) {
				images.add(null);
			} else {
				images.set(pos, null);
			}

		} else {
			iv.setImageBitmap(image);
			if (pos >= images.size()) {
				images.add(image);
			} else {
				images.set(pos, image);
			}
		}

	}
	
}
